const state = {
  loading: false,
  cancelTokens: [] // 存储请求取消标识
}

const mutations = {
  SET_LOADING: (state, status) => {
    state.loading = status
  },
  addCancelToken: (state, { url, cancel }) => {
    state.cancelTokens.push({ url, cancel })
  },
  removeCancelToken: (state, url) => {
    state.cancelTokens = state.cancelTokens.filter(item => item.url !== url)
  },
  clearCancelTokens: (state) => {
    state.cancelTokens = []
  }
}

const actions = {
  showLoading({ commit }) {
    commit('SET_LOADING', true)
  },
  hideLoading({ commit }) {
    commit('SET_LOADING', false)
  },
  // 取消所有请求
  cancelAllRequests({ state, commit }) {
    state.cancelTokens.forEach(item => {
      item.cancel('操作取消')
    })
    commit('clearCancelTokens')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 